import router,{asyncroutes} from '@/router';
const state={
    auth:localStorage.getItem('token') || sessionStorage.getItem('token') || '',
    loading:false,
    menulist:[],
};
const getters={
    tokken:(state) =>{
        return state.auth;
    },
    loading:(state)=>{
        return state.loading
    }
};
const mutations={
    setToken:(state,admin) =>{       
        let token=admin['token'];
        let username=admin['username'];
        
        let longtime=localStorage.getItem('longtime') || '';
        if(longtime)
        {
            //长期保存
            localStorage.setItem('token',token);
            localStorage.setItem('adminname',username);
        }
        else{
            sessionStorage.setItem('token',token);
            sessionStorage.setItem('adminname',username);
        }
        state['auth']=token;
    },
    clearToken:(state) => {
        localStorage.clear();
        sessionStorage.clear();
        state['auth']='';        
    },
    
    
    loadroutes: (state,biaoshi) => {
        //asyncroutes.forEach((r)=>router.addRoute(r));
        
        
         
        const routelist= selectroutes(asyncroutes,biaoshi);

        
        state.menulist=routelist;
         
        
        routelist.forEach((val)=>{                        
            router.addRoute('Index',val);            

        });
        
       

        
    },
    goLogin:()=>{
        router.push({path:'/'});
    },

    changeload: (state,status) => {
        state.loading=status;
    }


};
const actions={
    initauthor:({commit},info) => {
        
        commit('setToken',info);
        commit('loadroutes',info['biaoshi']);
        
    },
    setrouters:({commit},biaoshi) =>{
        commit('loadroutes',biaoshi);
    }
};

function selectroutes(routes,biaoshi){
    
    const routelist=[];
    routes.forEach((val)=>{        
        let meta=val.meta;
        let children=val.children;
       
        if(meta.auth.includes(biaoshi)){
           if(children.length>0){
            val.children=selectroutes(children,biaoshi);
           }
            routelist.push(val);
            
        }

        
        
    });

    return routelist;
}

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions,
  }